import os
import time
import socket as sk
from threading import Thread


def recv(sock,addr):
	print('recv a connect from %s %s' %addr)
	data = str(sock.recv(1024),'utf-8').split('|')
	op = data[0]
	if op=='send':
		towho = data[1]
		if os.path.exists(towho+'/cache'):
			os.remove(towho+'/cache')
		with open(towho+'/cache','wb') as f:
			while True:
				d = sock.recv(1024)
				if d:
					f.write(d)
				else:
					break
	elif op=='check':
		user = data[1]
		if os.path.exists(user+'/cache'):
			sock.sendall(bytes('yes','utf-8'))
		else:
			sock.sendall(bytes('no','utf-8'))

	elif op=='recv':
		user = data[1]
		time.sleep(0.1)
		with open(user+'/cache','rb') as f:
			sock.sendall(f.read())
		sock.close()
		os.remove(user+'/cache')






s = sk.socket(sk.AF_INET,sk.SOCK_STREAM)
s.bind(('0.0.0.0',5000))
s.listen()
print('服务器启动成功，正在等待连接...')

while True:
	sock, addr = s.accept()
	t = Thread(target=recv,args=(sock,addr))
	t.start()
















